#!/usr/bin/python
# -*- coding: UTF-8 -*-
import subprocess
import time
from kpautos.engine.case import Case
from kptest.config.enum import DeviceType, HostType, DeviceUtility


class IPMCSET_RESET_001(Case):
    """
            Name:
                IPMCSET_RESET_001
            Label:
                重启BMC管理系统
            PreCondition:
                BMC正常启动
            TestStep:
                1) 命令行执行 ipmcset -d reset，重启BMC
            ExpectedResult:
                A) BMC会重启，web有重启日志
            Parameters:

            Author:
                baixin liuya
            Last Modified:

            Remark:

        """

    # 测试执行前配置等准备操作
    def pre_test_case(self):
        self.logger.info("Pre Test Case Start.... ")
        self.device_dut = self.resource.get_device(device_type=DeviceType.Server, utility=DeviceUtility.DUT)
        self.bmc_host = self.device_dut.get_host(host_type=HostType.BMC)
        self.bmc_ip = self.bmc_host.local_ip

    # 测试步骤
    def procedure(self):
        self.log_step("Step1: 通过ipmcset -d reset重启BCM")
        resp = self.bmc_host.run({"command": ["ipmcset -d reset"], "timeout": 10})
        self.logger.info(resp)
        rc = resp['rc']
        if rc != 0:
            self.assertIsNotNone(None, "BMC控制台执行[ipmcget -d ipinfo]命令失败")

    # 测试结束后恢复环境
    def post_test_case(self):
        ping_timeout = 120
        interval = 2
        while ping_timeout > 0:
            try:
                # Windows系统使用'-n'参数，Linux使用'-c'
                result = subprocess.run(['ping', '-n', '1', self.bmc_ip],
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.PIPE,
                                        timeout=interval)

                # 返回码为0表示ping成功
                if result.returncode == 0:
                    break

            except subprocess.TimeoutExpired:
                pass

            time.sleep(interval)

        if ping_timeout < 0:
            self.logger.error(None, "BMC服务2分钟还未恢复")
        else:
            resp = self.bmc_host.run({"command": ["ipmcget -d ipinfo"], "timeout": 10})
            if resp['rc'] == 0:
                pass
            else:
                self.logger.error("BMC服务2分钟还完全未恢复")
                self.assertIsNotNone(None, "BMC服务还未恢复，请排查原因")